package com.liuzhilin.controller;

import com.liuzhilin.mapper.JDBC;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
/*
* 用户登录
* */
@WebServlet("/userLogin")
public class UserLogin extends HttpServlet{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        // 设置响应头，允许跨域请求
        Response.setCorsHeaders(response);
        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        // 将请求体中的 JSON 数据解析为 JSONObject
        JSONObject requestJson = new JSONObject(sb.toString());

        String username = requestJson.getString("username");
        String password = requestJson.getString("password");
        // 验证用户
        if (UserService.userLogin(username, password)) {
            // 登录成功
            String token = "some-generated-token"; // 假设生成了一个 token
            //返回用户名
            out.print("{\"token\": \"" + token + "\", \"message\": \"登录成功！\",\"username\": \" "+ username +"\"}");
            response.setStatus(200);
        } else {
            // 密码错误
            out.print("{\"message\": \"用户名不存在或密码错误！\"}");
            response.setStatus(400);
        }
    }
    // 处理OPTIONS请求
    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response){
        Response.setCorsHeaders(response);
    }
}
